package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.api.CartService;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    @Autowired
    CartService cartService;


    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        // 向下转型
        CreateOrderContext createOrderContext = ((CreateOrderContext) context);

        // 获取订单中每个商品的id和购买数量
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        Map<Long, Long> productIdAndNum = new HashMap<>();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            productIdAndNum.put(cartProductDto.getProductId(), cartProductDto.getProductNum());
        }

        // 调用购物车暴露的接口
        ClearCartItemRequest request = new ClearCartItemRequest();
        request.setUserId(createOrderContext.getUserId());
        request.setProductIdAndNum(productIdAndNum);
        ClearCartItemResponse response = cartService.clearCartItemByUserID(request);
        // 如果响应码为错误，抛异常
        if (!OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }

        return true;
    }
}
